package org.myy.learn.hot.回溯;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class 组合总和 {
    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        int len = candidates.length;
        if(len == 0){return result;}
        List<Integer> list = new ArrayList<>();
        backTrack(candidates, target, result, list, 0);
        return result;
    }

    public static void backTrack(int[] candidates, int target, List<List<Integer>> ans, List<Integer> combine, int idx) {
        if (idx == candidates.length) {return;}
        if (target == 0) {
            ans.add(new ArrayList<>(combine));
            return;
        }
        // 直接跳过
        backTrack(candidates, target, ans, combine, idx + 1);   //ToDo 目标值保持不变    只向下推一个位置
        // 选择当前数
        if (target - candidates[idx] >= 0) {
            combine.add(candidates[idx]);
            backTrack(candidates, target - candidates[idx], ans, combine, idx);
            combine.remove(combine.size() - 1);
        }
    }

    public static void main(String[] args) {
        int[] candidates = new int[]{2,3,6,7};
        List<List<Integer>> result = combinationSum(candidates, 7);
        log.info("执行结束，组合总和={}", result);
    }
}
